#pragma once 
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<unistd.h>
#include <iostream>
#include <string>
#include <cstring>

namespace wyl
{
    class TcpClient
    {
    public:
        TcpClient(const std::string& ip,const uint16_t& port):_sock(-1),_serverip(ip),_serverport(port){}
        ~TcpClient(){close(_sock);}

        void init()
        {
            _sock = socket(AF_INET,SOCK_STREAM,0);
            if(_sock < 0)
            {
                std::cout << "client create sock failed" << std::endl;
                exit(1); 
            }

            //无需显示绑定
            //无需监听 
        }

        void Runing()
        {

            //建立连接
            struct sockaddr_in svr; 
            svr.sin_family = AF_INET;
            svr.sin_port = htons(_serverport);
            svr.sin_addr.s_addr = inet_addr(_serverip.c_str());
            if(connect(_sock,(struct sockaddr*)&svr,sizeof svr) != 0) //connect会自动绑定端口
            {
                std::cout << "client connect failed" << std::endl;
                exit(2); 
            }

            //进行IO通信
            char message[1024] = {0};
            char readbuff[1024] = {0};
            while(1)
            {
                fgets(message,sizeof message - 1,stdin); 
                
                message[strlen(message) - 1] = 0 ; //去掉空行
                write(_sock,message,strlen(message)); 

                int n = read(_sock,readbuff,sizeof readbuff - 1); 
                if(n > 0)
                {
                    std::cout << readbuff << std::endl;
                }else break;
            }
        }
    private:
        int _sock; 
        std::string _serverip;
        uint16_t _serverport; 
    };
};